package com.erp.inv.input.controller;

import com.erp.cux.workflow.controller.CuxControllerSupport;
import com.erp.dataset.service.DatasetCommonService;
import com.erp.hr.base.vo.ResultVO;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.inv.input.dao.InvInputHeadDao;
import com.erp.inv.input.dao.model.*;
import com.erp.inv.input.service.InvInputHeadService;
import com.erp.inv.input.service.InvInputLineService;
import com.erp.inv.stock.dao.model.InvStock;
import com.erp.inv.stock.service.InvStockService;
import com.erp.inv.warehouse.dao.model.InvWarehouse;
import com.erp.inv.warehouse.service.InvWarehouseService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.order.supply.model.*;
import com.erp.order.supply.service.SupplyMaterialDetailService;
import com.erp.order.supply.service.SupplyMaterialRService;
import com.until.DateUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.util.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/web/invInputPda")
public class InvInputHeadPdaController extends CuxControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(InvInputHeadPdaController.class);
    
    //服务层注入
    @Autowired
    private InvInputHeadService invInputHeadService;
    @Autowired
    private InvInputLineService invInputLineService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private HrCommonService hrCommonService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private InvStockService invStockService;
    @Autowired
    private InvWarehouseService invWarehouseService;
    @Autowired
    private InvInputHeadDao invInputHeadDao;
    @Autowired
    private SupplyMaterialRService supplyMaterialRService;
    @Autowired
    private SupplyMaterialDetailService supplyMaterialDetailService;


    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getInvInputHeadList");
    }
    
    
    
    /**
     * 
     * @description 查询供货单数据列表
     * @date 2020-08-20 17:21:04
     * @author 
     * @param pages
     * @param invInputHeadCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("goSupplyMaterial")
    public String goSupplyMaterial(Pages pages, InvInputHeadCO invInputHeadCO, Model model) {
        model.addAttribute("invInputHeadCO", invInputHeadCO);
        return "pda/supplyMaterial";
    }
    
    

    
    
    
    /**
     * 
     * @description 根据送货单号查询送货信息
     * @return
     * @return String
     *
     */
    @RequestMapping("getSupplyMaterialData")
    @ResponseBody
    public Object getSupplyMaterialData(@RequestBody Map supplyMaterialId){
        try {
            //物料
            Map materialMap = this.masterDataCommonService.getMaterialMap();
            //物料单位
            Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
            SupplyMaterialVO supplyMaterial = this.invInputHeadService.getSupplyMaterialByCode((String)supplyMaterialId.get("supplyMaterialId"));
            List<SupplyMaterialDetailVO> supplyMaterialDetailList = this.invInputHeadService.getSupplyMaterialDetailByCode((String)supplyMaterialId.get("supplyMaterialId"));
            for(SupplyMaterialDetailVO supplyMaterialDetailVO: supplyMaterialDetailList) {
                supplyMaterialDetailVO.setMaterial_name(materialMap.get(supplyMaterialDetailVO.getMaterial_code()).toString());
            }
            Map supplyMaterialResp=new HashMap();
            supplyMaterialResp.put("supplyMaterial",supplyMaterial);
            supplyMaterialResp.put("supplyMaterialDetailList",supplyMaterialDetailList);
            supplyMaterialResp.put("code",0);
            if(supplyMaterial==null){
                return ResultVO.error("查询不到对应的供货单信息!");
            }
            else{
                return supplyMaterialResp;
            }
        }catch(Exception e) {
            return ResultVO.error(null,-1,"查询不到应用的供货单信息!");
        }
    }
    @RequestMapping("goSupplyMaterialDetail")
    public String goSupplyMaterialDetail(String supplyMaterialId,String id, Model model) {
        //物料
        Map materialMap = this.masterDataCommonService.getMaterialMap();
        //物料单位
        Map materialUnitMap = this.datasetCommonService.getMaterialUnit();
        SupplyMaterialVO supplyMaterial = this.invInputHeadService.getSupplyMaterialByCode(supplyMaterialId);
        SupplyMaterialDetailVO supplyMaterialDetail=this.invInputHeadService.getMaterialDetailByCode(id);
        supplyMaterialDetail.setMaterial_name(materialMap.get(supplyMaterialDetail.getMaterial_code()).toString());
        supplyMaterialDetail.setStandard_unit(materialUnitMap.get(supplyMaterialDetail.getStandard_unit()).toString());
        //获取物料规格
        //MdMaterial mdMaterial = this.masterDataCommonService.getMdMaterialInfoCache(supplyMaterialDetail.getStandard());
        //supplyMaterialDetail.setStandard(mdMaterial.getStandard());
        //仓库
        List<InvWarehouse> warehouseList = this.invWarehouseService.getDataObjects();
        Map<String, InvWarehouse> warehouseMap = new HashMap<String, InvWarehouse>();
        for(InvWarehouse invWarehouse: warehouseList) {
            warehouseMap.put(invWarehouse.getWarehouseCode(), invWarehouse);
        }
        HrStaffInfoRO hrStaffInfoRO=getLoginStaffInfo();
        model.addAttribute("staffInfo", hrStaffInfoRO);
        model.addAttribute("supplyMaterial", supplyMaterial);
        model.addAttribute("supplyMaterialDetail", supplyMaterialDetail);
        model.addAttribute("warehouseMap", warehouseMap);
        return "pda/supplyMaterialDetail";
    }

    @RequestMapping("save")
    public String save(String supplyMaterialDetailId,
                       String purchase_order_id,
                       String supplyMaterialId,
                       String numReally,
                       String sunhao,
                       String loss_memo,
                       String desc,
                       String warehouse,
                       Model model,
                       RedirectAttributes attr) {
        SupplyMaterialVO supplyMaterial = this.invInputHeadService.getSupplyMaterialByCode(purchase_order_id);
        SupplyMaterialRVO supplyMaterialR = this.invInputHeadService.getSupplyMaterialRByCode(supplyMaterialId);
        SupplyMaterialDetailVO supplyMaterialDetail = this.invInputHeadService.getSupplyMaterialDetailById(supplyMaterialDetailId);
        InvInputHead invInputHead=new InvInputHead();
        invInputHead.setInputHeadCode("IN" + "-" + DateFormatUtils.format(new Date(), "yyyyMMdd") + invInputHeadService.getNewHeadCodeByType("IN"));
        invInputHead.setInputType("IN");
        invInputHead.setInputSourceType("DISPATCH");//入库来源类型-发货单
        invInputHead.setInputSourceHeadCode("IN" + "-" + DateFormatUtils.format(new Date(), "yyyyMMdd") + invInputHeadService.getNewHeadCodeByType("IN"));
        invInputHead.setWarehouseCode(warehouse);
        invInputHead.setInputDate(DateUtils.strToDate(DateUtils.getNowDateShortString()));
        invInputHead.setMemo(desc);
        invInputHead.setVersion(1);
        invInputHead.setStatus("CONFIRM");
        invInputHead.setApproveStatus("CONFIRM");
        invInputHead.setStaffCode(this.getLoginStaffInfo().getStaffCode());
        invInputHead.setDepartmentCode(this.getLoginStaffInfo().getDepartmentCode());
        invInputHead.setIsDel("0");
        invInputHead.setCreatedDate(DateUtils.getSqlDate());
        invInputHead.setCreatedBy(this.getLoginStaffInfo().getStaffName());
        invInputHead.setOrgCode("jingneng");
        //保存明细信息
        InvInputLine invInputLine=new InvInputLine();
        invInputLine.setInputLineCode(SnowFlake.getConcurrentId().toString());
        invInputLine.setInputHeadCode("IN" + "-" + DateFormatUtils.format(new Date(), "yyyyMMdd") + invInputHeadService.getNewHeadCodeByType("IN"));
        //送货单ID
        invInputLine.setInputSourceLineCode(purchase_order_id);
        invInputLine.setMaterialCode(supplyMaterialDetail.getMaterial_code());
        //应输入量
        invInputLine.setQuantity(new BigDecimal(supplyMaterialDetail.getNum()));
        //实际入库量
        invInputLine.setInputQuantity(new BigDecimal(numReally));
        //单价
        invInputLine.setPrice(new BigDecimal(supplyMaterialDetail.getPrice()));
        //AMOUNT 行金额=数量*单价
        invInputLine.setAmount(new BigDecimal(supplyMaterialDetail.getPrice()).multiply(new BigDecimal(supplyMaterialDetail.getPrice())));
        //赠送说明 如果实际入库量大于送货量则设置赠送量
        invInputLine.setAttachedMemo("");
        //折扣率
        invInputLine.setDiscount("0");
        //折扣原因
        invInputLine.setDiscountMemo("");
        //0默认有质检报告
        invInputLine.setIsReport("0");
        //1:直入直出 2:自动生成出库单 3:进入库存
        invInputLine.setInvMeans("3");
        invInputLine.setUnit(supplyMaterialDetail.getStandard_unit());
        invInputLine.setMemo(desc);
        invInputLine.setVersion(1);
        invInputLine.setStatus("Y");
        invInputLine.setIsDel("0");
        invInputLine.setCreatedDate(DateUtils.getSqlDate());
        invInputLine.setCreatedBy(this.getLoginStaffInfo().getStaffName());
        invInputLine.setOrgCode("jingneng");
        invInputLine.setLoss(sunhao);
        invInputLine.setLossMemo(loss_memo);
        invInputLine.setHeadInputType("INPUT");
        //保存编辑的数据
        this.invInputHeadService.insertOrUpdateDataObject(invInputHead);
        //插入入库单明细和库存表
        this.invInputLineService.insertOrUpdateDataObject(invInputLine);
         //将数据保存至库存表
        Pages pages = new Pages();
        pages.setPage(1);
        pages.setMax(1000);
        InvInputLineCO invInputLineCO = new InvInputLineCO();
        invInputLineCO.setInputHeadCode(invInputHead.getInputHeadCode());
        //获取头
        InvStock stock = new InvStock();
        stock.setBillHeadCode(invInputHead.getInputHeadCode());
        stock.setBillLineCode(invInputLine.getInputLineCode());
        stock.setMaterialCode(invInputLine.getMaterialCode());
        stock.setStockCode(SnowFlake.getConcurrentId().toString());
        stock.setWarehouseCode(invInputHead.getWarehouseCode());
        stock.setBillType("INPUT");
        stock.setMemo("入库单自动创建");
        stock.setStockNumber(invInputLine.getInputQuantity());
        //获取当前用户职员信息
        HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
        stock.setStaffCode(staffInfo.getStaffCode());
        stock.setDepartmentCode(staffInfo.getDepartmentCode());
        this.invStockService.insertDataObject(stock);
        //物资入库完成后将送货表中的物资明细改为入库状态
        SupplyMaterialDetail supplyMaterialDetailInfo=new SupplyMaterialDetail();
        supplyMaterialDetailInfo.setId(Long.parseLong(supplyMaterialDetail.getId()));
        //将本条物资状态分配成已入库状态
        supplyMaterialDetailInfo.setStatus("0");
        supplyMaterialDetailService.updateDataObject(supplyMaterialDetailInfo);
        //判断该批送货单是否已经全部入库 如果全部入库则修改主表送货单状态
        if(invInputHeadService.getSupplyMaterialStatusCount(purchase_order_id)==0){
            SupplyMaterialR supplyMaterialRInfo=new SupplyMaterialR();
            supplyMaterialRInfo.setId(Long.parseLong(supplyMaterialR.getId()));
            supplyMaterialRInfo.setStatus("0");
            supplyMaterialRService.update(supplyMaterialRInfo);
        }
        attr.addAttribute("inputHeadCode",purchase_order_id);
        return "redirect:goSupplyMaterial";
    }

}
